<template>
  <div ref="divContainer">
    <el-input
      v-model="filterText"
      prefix-icon="el-icon-search"
      placeholder="筛选"
      clearable
      size="small"
      style="margin-bottom: 5px;"
      maxlength="30"
    />
    <el-scrollbar
      ref="scroll"
      :style="{ height: domHeight + 'px'}"
    >
      <el-tree
        ref="tableList"
        :data="this.tableList"
        lazy
        :load="handleLazyLoad"
        :props="this.tableListProps"
        :filter-node-method="filterNode"
        node-key="id"
        :check-on-click-node="true"
        :default-expand-all="false"
        :highlight-current="true"
        @current-change="currentChangeHandler"
      >
        <template #default="{ node, data }">
          <div class="custom-tree-node">
            <span class="node-icon">
              <svg-icon v-if="node.level===2" icon-class="icon-datasource"/>
              <svg-icon v-else-if="node.level>2" icon-class="icon-table"/>
              <svg-icon v-else-if="node.expanded" icon-class="icon-opened"/>
              <svg-icon v-else="!node.expanded" icon-class="icon-closed"/>
            </span>
            <span>
              {{
                data.type === '1' ? (data.remark === data.name ? data.remark : data.remark + '(' + data.name + ')') : data.remark
              }}
            </span>
          </div>
        </template>
      </el-tree>
    </el-scrollbar>
  </div>
</template>

<script>
import httpRequest from '../../../../../utils/studioRequest'
export default {
  components: {},
  props: {},
  data() {
    return {
      domHeight: 360,
      filterText: '',
      flinkDataList: [],
      tableList: [],
      tableListProps: {
        label: 'name',
        children: 'children',
        isLeaf: 'isLeaf'
      }
    }
  },
  computed: {},
  watch: {
    filterText(val) {
      this.$refs.tableList.filter(val)
    }
  },
  mounted() {
    this.$nextTick(function() {
      var heightCss = window.getComputedStyle(this.$refs.divContainer).height
      if (heightCss === 'auto') {
        this.domHeight = document.documentElement['clientHeight'] - 226
      }
    })
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      const vFlinkDataBasePostData = {
        'page': 1,
        'pageSize': 99,
        'filters': {
          'name': '',
          'type': '',
          'groupName': '',
          'status': '',
          'enabled': ''
        },
        'sorts': []
      }
      this.filterText = ''
      httpRequest({
        url: httpRequest.adornFlinkUrl(`/database/page`),
        method: 'post',
        data: httpRequest.adornData(vFlinkDataBasePostData)
      }).then(({ data }) => {
        if (data && (data.code === 0 || data.code === 200)) {
          this.flinkDataList = this.flinkDataToTreeData(data)
          this.tableList = this.flinkDataList
        } else {
          this.tableList = []
        }
      })
    },
    flinkDataToTreeData(data) {
      const dataList = []
      // 组织数据源分组
      const group = []
      for (const item of data.data.list) {
        if (group === null || group.length <= 0) {
          group.push(item.groupName)
          continue
        }
        const index = group.findIndex((value, index) => value === item.groupName)
        if (index < 0) {
          group.push(item.groupName)
        }
      }
      // 组织子集
      for (let i = 0; i < group.length; i++) {
        const lGroupChildList = []
        for (const item of data.data.list) {
          if (item.groupName === group[i]) {
            lGroupChildList.push({
              checked: null,
              _level: 1,
              id: item.id,
              name: item.name,
              open: null,
              parentId: '0_' + i,
              remark: item.name,
              type: item.type
            })
          }
        }
        const lGroupData = {
          checked: null,
          _level: 0,
          id: '0_' + i,
          name: group[i],
          open: null,
          parentId: '0',
          remark: group[i],
          type: null,
          children: lGroupChildList
        }
        //
        dataList.push(lGroupData)
      }
      // 返回值
      return dataList
    },
    getDatasource(resolve) {

    },
    handleLazyLoad(node, resolve) {
      switch (node.level) {
        case 0:
          this.getDatasource(resolve)
          return
        case 1:
          return resolve(node.data.children)
        case 2:
          this.getTableList(node.data.id, resolve, node)
          return
      }
      return resolve([])
    },
    getTableList(id, resolve, parentNode) {
      const lDataBaseName = parentNode.data.name
      httpRequest({
        url: httpRequest.adornFlinkUrl(`/database/getSchemasAndTables`),
        method: 'get',
        params: httpRequest.adornParams({
          id: id
        }, false)
      }).then(({ data }) => {
        if (data && data.code === 200) {
          const list = []
          for (const item of data.data[0].tables) {
            list.push({
              label: item.name,
              dataBaseName: lDataBaseName,
              _level: 2,
              checked: null,
              id: item.name,
              comment: item.comment,
              name: item.name,
              open: null,
              parentId: id,
              remark: item.name,
              type: '1',
              schema: item.schema,
              schemaTableName: item.schemaTableName,
              schemaTableNameWithUnderline: item.schemaTableNameWithUnderline,
              isLeaf: true
            })
          }
          resolve(list)
        } else {
          resolve([])
          this.$message.error(data.message)
        }
      })
    },
    /** *
     * 外部设置过滤
     * @text
     */
    filter(text) {
      this.filterText = text
    },
    currentChangeHandler(data, node) {
      if (node.level === 2) {
        this.$emit('srcSelectHandler', data)
      } else if (node.level === 3) {
        // 选择表节点，调用父组件函数
        this.$emit('tableSelectHandler', data, node)
      }
    },
    /** *
     * 根据节点ID获取节点名称
     * @param id
     */
    getName(id) {
      var node = this.$refs.tableList.getNode(id)
      if (node) {
        this.$refs.tableList.setCurrentKey(id)
        return node.data.name
      }
      return ''
    },
    /** *
     * 树节点过滤
     */
    filterNode(value, data) {
      if (!value) return true
      var values = []
      if (value.indexOf(',') > -1) {
        value = value.toLowerCase()
        values = value.split(',')
      } else {
        values.push(value)
      }
      for (var i = 0; i < values.length; i++) {
        if (data.name.toLowerCase().indexOf(values[i]) !== -1 || data.remark.toUpperCase().indexOf(values[i]) !== -1) {
          return true
        }
      }
    }
    // method end //////////////////////
  }
}
</script>

<style scoped>

</style>
